package com.xkstream.client.ui.live.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.util.Log;
import android.view.TextureView;
import android.view.View;

import com.xkstream.client.R;
import com.xkstream.client.application.Application;
import com.xkstream.client.appmanager.AppManager;
import com.xkstream.client.base.BaseFragment;
import com.xkstream.client.entity.User;
import com.xkstream.client.rx.Rxbus;
import com.xkstream.client.ui.live.LiveEndActivity;
import com.xkstream.client.ui.live.LiveHelper;
import com.xkstream.client.utils.DeviceUtils;
import com.xkstream.client.utils.LogUtil;
import com.xkstream.client.utils.NetUtil;
import com.zego.zegoliveroom.callback.IZegoLiveEventCallback;
import com.zego.zegoliveroom.callback.IZegoLivePublisherCallback;
import com.zego.zegoliveroom.callback.IZegoLoginCompletionCallback;
import com.zego.zegoliveroom.callback.IZegoRoomCallback;
import com.zego.zegoliveroom.constants.ZegoBeauty;
import com.zego.zegoliveroom.constants.ZegoConstants;
import com.zego.zegoliveroom.constants.ZegoVideoViewMode;
import com.zego.zegoliveroom.entity.AuxData;
import com.zego.zegoliveroom.entity.ZegoStreamInfo;
import com.zego.zegoliveroom.entity.ZegoStreamQuality;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;

import static com.xkstream.client.application.Application.mZegoLiveRoom;

/**
 * Created by xiaoyi on 2017-10-9.
 */

public class LivePreviewFragment extends BaseFragment {
    @BindView(R.id.texturePreview)
    TextureView tvPreview;


    boolean needRepaire = false;
    private long startTime;
    NetworkReceiver receiver;
    private boolean isFront = true;

    private int gameType;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_live_preview;
    }

    int beauty = 3;

    @Override
    public void initViews(View root) {
        registerNetworkBrocastRecevier();
        gameType = getArguments().getInt("gameType");

        prepareLive();

        Rxbus.getDefault().register(String.class)
                .subscribe((s -> {
                    if (!isAdded()) return;
                    if (s.equals("exit")) {
                        Bitmap bitmap = tvPreview.getBitmap(DeviceUtils.dp2px(mActivity, 360 / 3),
                                DeviceUtils.dp2px(mActivity, 640 / 3));
                        Intent intent = new Intent(mActivity, LiveEndActivity.class);
                        LiveHelper.bitmap = bitmap;
                        intent.putExtra("starttime", startTime);
                        AppManager.getAppManager().finishActivity();
                        startActivity(intent);
                    }
                }));
    }


    private void prepareLive() {
        mZegoLiveRoom.setPreviewView(tvPreview);
        mZegoLiveRoom.startPreview();
        mZegoLiveRoom.enablePreviewMirror(true);
        mZegoLiveRoom.enableCaptureMirror(false);
        mZegoLiveRoom.setPreviewViewMode(ZegoVideoViewMode.ScaleAspectFill);
        mZegoLiveRoom.setZegoRoomCallback(new IZegoRoomCallback() {
            @Override
            public void onKickOut(int i, String s) {
                Log.e(TAG, String.format("onKickOut code %d  msg:%s", i, s));
                AppManager.getAppManager().finishActivity();
                if (tvPreview == null) return;
                Bitmap bitmap = tvPreview.getBitmap(DeviceUtils.dp2px(mActivity, 360 / 3),
                        DeviceUtils.dp2px(mActivity, 640 / 3));
                Intent intent = new Intent(mActivity, LiveEndActivity.class);
                LiveHelper.bitmap = bitmap;
                intent.putExtra("starttime", startTime);
                showToast(R.string.kickout);
                startActivity(intent);
            }

            @Override
            public void onDisconnect(int i, String s) {
                needRepaire = true;
                Log.e(TAG, String.format("onDisconnect code %d  msg:%s", i, s));
                showToast(R.string.reconnecting);
                User user = Application.getUser();
                mZegoLiveRoom.startPublishing(user.getAnchor().getStream_id(), user.getExt_info().getNickname(), ZegoConstants.PublishFlag.JoinPublish);
            }

            @Override
            public void onReconnect(int i, String s) {

            }

            @Override
            public void onTempBroken(int i, String s) {

            }

            @Override
            public void onStreamUpdated(int i, ZegoStreamInfo[] zegoStreamInfos, String s) {

            }

            @Override
            public void onStreamExtraInfoUpdated(ZegoStreamInfo[] zegoStreamInfos, String s) {

            }

            @Override
            public void onRecvCustomCommand(String s, String s1, String s2, String s3) {

            }
        });
        final User user = Application.getUser();
        mZegoLiveRoom.loginRoom("roomId:" + user.getAnchor().getRoom_id_pk(), ZegoConstants.RoomRole.Anchor, new IZegoLoginCompletionCallback() {
            @Override
            public void onLoginCompletion(int i, ZegoStreamInfo[] zegoStreamInfos) {
                if (i == 0) {
                    // 登录成功
                    // 调用startPublish开始直播，flag是直播属性
                    mZegoLiveRoom.startPublishing(user.getAnchor().getStream_id(), user.getExt_info().getNickname(), ZegoConstants.PublishFlag.JoinPublish);
                    startTime = System.currentTimeMillis();
                    LogUtil.e(TAG, "登录成功 " + zegoStreamInfos);
                } else {

                    // 登录失败, 业务侧打印日
                    LogUtil.e(TAG, "登录失败 " + zegoStreamInfos);
                }
            }
        });
        mZegoLiveRoom.setZegoLiveEventCallback(new IZegoLiveEventCallback() {
            @Override
            public void onLiveEvent(int i, HashMap<String, String> hashMap) {
                Log.e(TAG, String.format("onLiveEvent  code %d", i));
                StringBuilder sb = new StringBuilder("onLiveEvent  msg : ");
                for (String key : hashMap.keySet()) {
                    sb.append(key).append(" : ").append(hashMap.get(sb)).append("\n");
                }
                Log.e(TAG, sb.toString());
            }
        });
        mZegoLiveRoom.setZegoLivePublisherCallback(new IZegoLivePublisherCallback() {
            @Override
            public void onPublishStateUpdate(int i, String s, HashMap<String, Object> hashMap) {
                Log.e(TAG, String.format("onPublishStateUpdate code : %d\n msg : %s", i, s));
                if (i > 0) {
                    AppManager.getAppManager().finishActivity();
                    LogUtil.e(TAG, "onPublishStateUpdate 流断开");
                }
            }

            @Override
            public void onJoinLiveRequest(int i, String s, String s1, String s2) {
                Log.e(TAG, String.format("onJoinLiveRequest s1 : %s  s2 : ", s1, s2));
            }

            @Override
            public void onPublishQualityUpdate(String s, ZegoStreamQuality zegoStreamQuality) {
                LogUtil.e(TAG, String.format("onPublishQualityUpdate : %s  s2 : ", s));
                LogUtil.e(TAG, String.format("Quality:%s VideoBitrate:%s VideoFPS:%s", zegoStreamQuality.quality,
                        zegoStreamQuality.videoBitrate, zegoStreamQuality.videoFPS));
                if (zegoStreamQuality.quality == 3) {
                        /*if (inTimeZone(Calendar.getInstance().get(Calendar.SECOND) - badNetworkSeconds, 3)) {
                            badNetwork++;
                        } else {
                            badNetwork = 0;
                        }
                        badNetworkSeconds = Calendar.getInstance().get(Calendar.SECOND);*/

                }
            }

            @Override
            public AuxData onAuxCallback(int i) {
                return null;
            }

            @Override
            public void onCaptureVideoSizeChangedTo(int i, int i1) {

            }

            @Override
            public void onMixStreamConfigUpdate(int i, String s, HashMap<String, Object> hashMap) {

            }
        });

        mZegoLiveRoom.enableBeautifying(ZegoBeauty.POLISH | ZegoBeauty.WHITEN);
//        mZegoLiveRoom.setWhitenFactor(1);
//        mZegoLiveRoom.setSharpenFactor(2);
//        mZegoLiveRoom.setPolishStep(1);
//        mZegoLiveRoom.setPolishFactor(1);
        Log.e(TAG, String.format("push sound level : %f ", mZegoLiveRoom.getCaptureSoundLevel()));


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mActivity.unregisterReceiver(receiver);
        mZegoLiveRoom.stopPublishing();
    }

    private class NetworkReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String NET_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
            Log.e("NetBroadcastReceiver", "onReceive");
            if (intent.getAction().equals(NET_CHANGE_ACTION)) {
                int netWorkState = NetUtil.getNetworkState(context);
                Log.e("NetBroadcastReceiver", "onReceive" + netWorkState);
                // 接口回调传过去状态的类型
                onNetChange(netWorkState);
            }
        }
    }

    private void onNetChange(int netWorkState) {
        if (isNetConnect(netWorkState) && needRepaire) {
            needRepaire = false;
            prepareLive();
        }
    }

    private void registerNetworkBrocastRecevier() {
        receiver = new NetworkReceiver();
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        mActivity.registerReceiver(receiver, filter);
    }

    /**
     * 判断有无网络 。
     *
     * @return true 有网, false 没有网络.
     */
    public boolean isNetConnect(int code) {
        if (code == 1) {
            return true;
        } else if (code == 2) {
            return true;
        } else if (code == 0) {
            return false;
        }
        return false;
    }

    @OnClick({R.id.ivSwitch, R.id.ivClose, R.id.root})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivClose:
                mActivity.onBackPressed();
                break;
            case R.id.ivSwitch:
                mZegoLiveRoom.setFrontCam(isFront = !isFront);
                break;
            case R.id.root:
                Rxbus.getDefault().post("onclick");
                break;
        }
    }
}
